import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
from src.core import items as items_core

def show_selection_screen(parent, item_manager):
    """Display all bakery items"""
    for widget in parent.winfo_children():
        widget.destroy()
    
    # Header
    header_frame = tk.Frame(parent, bg="#DDF6F8")
    header_frame.pack(fill=tk.X, pady=10)
    
    title = tk.Label(header_frame, text="🍞 Our Fresh Menu", 
                     font=("Arial", 28, "bold"), 
                     bg="#DDF6F8", fg="#4A3728")
    title.pack(side=tk.LEFT, padx=20)
    
    from src.ui.tkinter.screens.launch_screen import show_launch_screen
    back_btn = tk.Button(header_frame, text="← Back", 
                         command=lambda: show_launch_screen(parent, item_manager),
                         font=("Arial", 12), bg="#C49B6D", fg="white",
                         relief=tk.RAISED, bd=2)
    back_btn.pack(side=tk.RIGHT, padx=20)
    
    # Search bar
    search_frame = tk.Frame(parent, bg="#DDF6F8")
    search_frame.pack(fill=tk.X, padx=20, pady=(10, 10))
    tk.Label(search_frame, text="🔍 Search:", font=("Arial", 12), bg="#DDF6F8", fg="#4A3728").pack(side=tk.LEFT, padx=(0, 8))
    search_entry = tk.Entry(search_frame, font=("Arial", 11), relief=tk.SOLID, bd=2)
    search_entry.pack(side=tk.LEFT, fill=tk.X, expand=True)
    
    # Items display frame with scrollbar
    canvas_frame = tk.Frame(parent, bg="#DDF6F8")
    canvas_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=20)
    
    canvas = tk.Canvas(canvas_frame, bg="#DDF6F8", highlightthickness=0)
    scrollbar = ttk.Scrollbar(canvas_frame, orient="vertical", command=canvas.yview)
    scrollable_frame = tk.Frame(canvas)
    
    scrollable_frame.bind(
        "<Configure>",
        lambda e: canvas.configure(scrollregion=canvas.bbox("all"))
    )
    
    canvas.create_window((0, 0), window=scrollable_frame, anchor="nw")
    canvas.configure(yscrollcommand=scrollbar.set)
    
    def render_items(items_to_show):
        for widget in scrollable_frame.winfo_children():
            widget.destroy()
        if not items_to_show:
            empty_label = tk.Label(scrollable_frame, text="No items found.", 
                                   font=("Arial", 14), bg="#DDF6F8", fg="#666")
            empty_label.pack(pady=50)
            return None
        def start_bread_animation(label_var):
            frames = ["🥐   ", "  🥐 ", "   🥐"]
            idx = 0
            def step():
                nonlocal idx
                label_var.set(frames[idx])
                idx = (idx + 1) % len(frames)
                parent.after(300, step)
            step()
        for idx, item in enumerate(items_to_show):
            card_bg = "#FFFFFF"
            item_frame = tk.Frame(scrollable_frame, bg=card_bg, 
                                 relief=tk.RIDGE, bd=2, padx=18, pady=14)
            item_frame.pack(fill=tk.X, pady=10, padx=4)
            info_text = f"ID: {item['id']}. {item['name']}\n"
            info_text += f"Price: ${item['price']:.2f} | Made: {item['production_date']}"
            icon_var = tk.StringVar(value="🥐   ")
            icon_label = tk.Label(item_frame, textvariable=icon_var, font=("Arial", 16), bg=card_bg)
            icon_label.pack(side=tk.LEFT, padx=(0, 10))
            start_bread_animation(icon_var)
            info_label = tk.Label(item_frame, text=info_text, 
                                  font=("Arial", 12), bg=card_bg, fg="#333",
                                  anchor="w", justify=tk.LEFT)
            info_label.pack(side=tk.LEFT, fill=tk.X, expand=True)
            delete_btn = tk.Button(item_frame, text="Delete", 
                                   command=lambda iid=item['id']: delete_item(parent, item_manager, iid),
                                   font=("Arial", 10, "bold"), bg="#DC3545", fg="white",
                                   width=10, relief=tk.RAISED, bd=2)
            delete_btn.pack(side=tk.RIGHT, padx=10)
        return None
    
    # Display items
    items = items_core.list_items(item_manager)
    render_items(items)
    
    def on_search_change(event=None):
        query = search_entry.get().lower().strip()
        if not query:
            render_items(items)
        else:
            filtered = [it for it in items if query in it['name'].lower() or query in str(it['id'])]
            render_items(filtered)
        return None
    
    search_entry.bind("<KeyRelease>", on_search_change)
    
    canvas.pack(side="left", fill="both", expand=True)
    scrollbar.pack(side="right", fill="y")
    
    parent.configure(bg="#DDF6F8")
    return None

def delete_item(parent, item_manager, item_id):
    """Called when user clicks Delete button"""
    success, msg = items_core.delete_item(item_manager, item_id)
    if success:
        messagebox.showinfo("Success", msg)
        show_selection_screen(parent, item_manager)
    else:
        messagebox.showerror("Error", msg)
    return None

